package com.jicheng.interceptor;

import com.jicheng.Enum.MenuEnum;
import com.jicheng.Utils.JWTUtil;
import com.jicheng.Utils.ServerUtil;
import com.jicheng.Utils.SpringUtils;
import com.jicheng.constants.Constants;
import com.jicheng.entity.SysLogDetail;
import com.jicheng.mapper.SysLogDetailMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: LogInterceptor
 * @Description: TODO
 * @author: khz
 * @date: 2020年10月13日 17:20
 */
public class LogInterceptor implements HandlerInterceptor {
    //请求日志实体标识
    private static final String LOGGER_ENTITY = "_logger_entity";

    /**
     * 进入SpringMVC的Controller之前开始记录日志实体
     * @param request 请求对象
     * @param response 响应对象
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //创建日志实体
        SysLogDetail sysLogDetail = new SysLogDetail();


        // 设置IP地址
        sysLogDetail.setOperationIp(ServerUtil.getRemortIP(request));

        //设置用户名
        sysLogDetail.setUsername(JWTUtil.getUsername(request.getHeader("Token")));

        //设置token
        sysLogDetail.setToken(request.getHeader("Token"));
        //设置操作模块
        sysLogDetail.setOperationModule(MenuEnum.parse(request.getRequestURI())==null?request.getRequestURI():MenuEnum.parse(request.getRequestURI()).getName());

        //设置操作内容
        sysLogDetail.setOperatingContent(MenuEnum.parse(request.getRequestURI())==null?request.getRequestURI():MenuEnum.parse(request.getRequestURI()).getOperation());


        //设置请求实体到request内，方便afterCompletion方法调用
        request.setAttribute(LOGGER_ENTITY,sysLogDetail);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

        //得到bean
        SysLogDetailMapper sysLogDetailMapper = (SysLogDetailMapper) SpringUtils.getBean("sysLogDetailMapper");

        //获取本次请求日志实体
        SysLogDetail sysLogDetail = (SysLogDetail) request.getAttribute(LOGGER_ENTITY);
        sysLogDetailMapper.insertSelective(sysLogDetail);

    }


    public static void main(String args[]){
        MenuEnum parse = MenuEnum.parse("/ino-query/getAppUser");
        System.out.print(parse);
    }
}
